package com.ljy.my_study.java.juc.forkjoinpool;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author lijunying
 * @date 2021/2/3 8:32
 */
public class SumTask extends RecursiveTask<Long> {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        SumTask sumTask=new SumTask(1000000000L);
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        Instant start = Instant.now();
        Future<Long> future=forkJoinPool.submit(sumTask);
        System.out.println(future.get());
        Instant end = Instant.now();
        System.out.println("use time:"+Duration.between(start, end).toMillis()+"ms");
        forkJoinPool.shutdown();
    }

//    private static final long THRESHOLD=1000000000L;
    private static final long THRESHOLD=100000L;

    private long start;
    private long end;

    public SumTask(long n){
        this(1,n);
    }

    public SumTask(long start,long end){
        this.start=start;
        this.end=end;
    }

    @Override
    protected Long compute() {
        long sum=0;
        if((end-start)<=THRESHOLD){
            for(long i=start;i<=end;i++){
                sum+=i;
            }
        }else{
            long mid=(start+end)>>>1;
            SumTask left=new SumTask(start,mid);
            SumTask right=new SumTask(mid+1,end);
            left.fork();
            right.fork();
            sum+=left.join()+right.join();
        }
        return sum;
    }
}
